﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Hybrid.Threading.Sync
{
    class ConditionVariablePattern
    {
        private readonly object m_lock = new object();
        private bool m_condition = false;

        public void Thread1()
        {
            Monitor.Enter(m_lock);//获取一个互斥锁
            //在锁中,原子性地测试复合条件
            while (!m_condition)
            {
                //如果条件不满足,等待另一个线程更改条件
                Monitor.Wait(m_lock);//临时释放锁,使其他线程能获取它
            }
            //条件满足,处理数据...
            Monitor.Exit(m_lock);//永久释放锁
        }

        public void Thread2()
        {
            Monitor.Enter(m_lock);//获取一个互斥锁
            //处理数据并修改条件
            m_condition = true;

            Monitor.PulseAll(m_lock);//锁释放后唤醒正在等待的线程

            Monitor.Exit(m_lock);//永久释放锁
        }
    }
}
